import 'package:flutter/material.dart';
import './readListItem.dart';
import 'dart:convert';
import 'dart:async';
import 'dart:io';

class ReadTabPage extends StatefulWidget {
  ReadTabPage({Key key, this.category}) : super(key: key);
  final String category;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _ReadTabPageState();
  }
}

class _ReadTabPageState extends State<ReadTabPage> {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = new GlobalKey<RefreshIndicatorState>();

  final String _url = 'http://v.juhe.cn/toutiao/index?type=toutiao&key=3a86f36bd3ecac8a51135ded5eebe862';

  List _news;

  //HTTP请求的函数返回值为异步控件Future
  Future<String> get(String category) async {
    var httpClient = new HttpClient();
    var request = await httpClient.getUrl(Uri.parse(_url));
    var response = await request.close();
    return await response.transform(utf8.decoder).join();
  }

  //下拉刷新调用的方法
  Future<Null> loadData() async {
    await get(widget.category); //注意await关键字
    if (!mounted) return; //异步处理，防止报错
    setState(() {}); //什么都不做，只为触发RefreshIndicator的子控件刷新
  }

  //接收到数据后构建列表页面
  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
    _news = jsonDecode(snapshot.data)['result'] != null ? jsonDecode(snapshot.data)['result']['data'] : [''];
    switch (_news.length) {
      case 1: //没有获取到数据，则返回请求失败的原因
        return new Center(
          child: new Card(
            child: new Text(jsonDecode(snapshot.data)['reason']),
          ),
        );
      default:
        return new ListView.builder(
          itemBuilder: (_, i) {
            return new Column(
              children: <Widget>[
                new ReadListItem(
                  title: _news[i]['title'],
                  authorName: _news[i]['author_name'],
                  pic: _news[i]['thumbnail_pic_s'],
                  handleLike: _handleLike,
                ),
                new Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6.0),
                  child: new Divider(
                    height: 1.0,
                  ),
                ),
              ],
            );
          },
          itemCount: _news.length,
        );
    }
  }

  _handleLike() {}

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.category);
  }

  @override
  Widget build(BuildContext context) {
    return new RefreshIndicator(
        child: new FutureBuilder(
          //用于懒加载的FutureBuilder对象
          future: get(widget.category), //HTTP请求获取数据，将被AsyncSnapshot对象监视
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none: //get未执行时
              case ConnectionState.waiting: //get正在执行时
                return new Center(
                  child: new Card(
                    child: new Text('loading...'), //在页面中央显示正在加载
                  ),
                );
              default:
                if (snapshot.hasError) //get执行完成但出现异常
                  return new Text('Error: ${snapshot.error}');
                else //get正常执行完成
                  // 创建列表，列表数据来源于snapshot的返回值，而snapshot就是get(widget.newsType)执行完毕时的快照
                  // get(widget.newsType)执行完毕时的快照即函数最后的返回值。
                  return createListView(context, snapshot);
            }
          },
        ),
        onRefresh: loadData,
        key: _refreshIndicatorKey);
  }
}
